package whu.cn.whushare.ui.main.known;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import whu.cn.whushare.R;
import whu.cn.whushare.common.Constants;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.BaseActivity;
import whu.cn.whushare.ui.common.LoadingHelper;
import whu.cn.whushare.ui.main.known.adapter.AnswerListAdapter;
import whu.cn.whushare.ui.main.known.adapter.TopicAdapter;
import whu.cn.whushare.ui.main.known.bean.AnswerWrapBean;
import whu.cn.whushare.ui.main.known.bean.FavorBean;
import whu.cn.whushare.ui.main.known.bean.QuestionDetail;
import whu.cn.whushare.ui.main.known.bean.Topic;
import whu.cn.whushare.util.SetOnClickUtil;
import whu.cn.whushare.util.Utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;
import com.dd.processbutton.iml.ActionProcessButton;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

@ViewMapping(id = R.layout.activity_answer_question_detail)     //获取activity_answer_question_detail布局文件
public class QuestionDetailActivity extends BaseActivity {
	private LoadingHelper mLoadingHelper;                       //用于加载问题详情主页面
	private LoadingHelper mAnswerLoadingHelper;                 //用于加载回答列表
	private String mQuestionId;                                 //问题id
    @ViewMapping(id = R.id.question_title)                      //获取“问题标题”文本框
    private TextView mQuestionTitle;
	@ViewMapping(id = R.id.question)                            //获取“问题内容”文本框
	private TextView mQuestionTxt;
	@ViewMapping(id = R.id.topics)                              //获取“话题列表”视图
	private GridView mTopicGrid;
	@ViewMapping(id = R.id.topic_go)                            //获取跳转到话题的图片
	private ImageView mTopicGoImg;
	@ViewMapping(id = R.id.answer_count)                        //获取“回答数”文本框
	private TextView mQuestionCountTxt;
	@ViewMapping(id = R.id.post_question_time)                  //获取“创建问题时间”文本框
	private TextView mPostQuesTimeTxt;
	@ViewMapping(id = R.id.btn_request_answer)                  //获取“邀请人回答”按钮
	private Button mRequestAnswerBtn;
	@ViewMapping(id = R.id.add_answer)                          //获取“添加回答”按钮
	private Button mAnswerBtn;
	@ViewMapping(id = R.id.answer_list)                         //获取回答列表
	private PullToRefreshListView mAnswerListView;
	@ViewMapping(id = R.id.main_content)                        //获取问题详情主页面视图
	private View mMainLayout;
	@ViewMapping(id = R.id.favor_btn)                           //获取“关注”按钮
	private ActionProcessButton mFavorBtn;
	private AnswerListAdapter adapter;
	private List<AnswerWrapBean> answerWrapBeans = new ArrayList<>();
	private boolean mHasInited;                                 //判断主页面是否已经初始化
	private boolean mHasAnswerInited;                           //判断回答列表是否已经初始化
	private boolean mIsFavored;                                 //判断是否已关注该问题
	private int mQuestionPage;
    private String mQuestionTex;
    private String mQuestionTitle0;
    private Integer answerCounts;
    private String html2="<p>";
	private final static int REQUEST_ADD_ANSWER = 2;

    //获取跳转到当前activity的intent信息，向intent中添加问题id
	public static Intent getStartIntent(Context context, String questionID) {
		Intent i = new Intent(context, QuestionDetailActivity.class);
		i.putExtra(Constants.INTENT_EXTRA_QUESTION_ID, questionID);

		return i;
	}

	@Override
    /**
     * 当该activity创建时调用该方法，完成activity的初始化操作
     * 调用{@link #getIntentData()}获取调用activity传递过来的问题id，从而展示对应id的问题详情
     * 调用{@link #initView()}对问题详情页面进行初始化
     * 调用{@link #getQuestionDetail()}创建获取问题详情的网络请求
     */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getIntentData();
		initView();
		getQuestionDetail();
	}

    //获取调用activity传递过来的问题id
	private void getIntentData() {
		if (getIntent() != null) {
			mQuestionId = getIntent().getStringExtra(Constants.INTENT_EXTRA_QUESTION_ID);
		}
	}

    /**
     * 对问题详情页面进行初始化：
     * 设置问题详情主页面布局，和retry刷新动作；
     * 设置回答列表页面布局和retry刷新动作；
     * 初始化“回答列表”，设置其刷新模式及刷新响应监听器，并设置列表项被选中时的动作为“跳转到回答详情页面”；
     */
	private void initView() {
		View root = ViewMappingUtil.mapView(this, this);  //将布局文件与当前activity一一映射
		SetOnClickUtil.registerOnClick(this);            //为当前activity中所声明的域对象设置OnClickListener
		getTopBar(root);
        mTopBar.title.setText("问题详情");
		initLoadingHelper();
		mFavorBtn.setMode(ActionProcessButton.Mode.ENDLESS);    //设置"关注"按钮模式
		initAnswerListView();
        mQuestionTxt.setOnClickListener(this);
	}

    /**
     * 初始化“回答列表”，设置其刷新模式及刷新响应监听器，并设置列表项被选中时的动作为“跳转到回答详情页面”
     */
	private void initAnswerListView() {
	    mAnswerListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);      //设置"回答列表"刷新模式为上滑刷新
        //设置“回答列表”刷新事件监听器，当监听到上滑刷新操作时，调用onRefresh方法进行处理
		mAnswerListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if (answerWrapBeans.size() >=mTotal) {
					Utils.setRefreshLabelToLast(QuestionDetailActivity.this, mAnswerListView);
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							mAnswerListView.onRefreshComplete();
						}
					}, 500);
				} else {
					getAnswerList();
				}
			}
		});
        //点击回答列表项时，跳转到回答详情页面
		mAnswerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				startActivity(AnswerDetailActivity.getStartIntent(QuestionDetailActivity.this, mQuestionId,
						mQuestionTitle0, adapter.getItem(position - 1)));
			}
		});
	}

    /**
     * 初始化LoadingHelper：
     * 设置mLoadingHelper布局文件为mMainLayout（即TopBar以下整个页面），retry监听器动作为创建获取问题详情的请求；
     * 设置mAnswerLoadingHelper布局文件为mAnswerListView（即回答列表），retry监听器动作为创建获取回答列表的请求；
     */
	private void initLoadingHelper() {
		mLoadingHelper = new LoadingHelper(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				getQuestionDetail();
			}
		});
		mLoadingHelper.onCreateView(LayoutInflater.from(this), mMainLayout);
		mAnswerLoadingHelper = new LoadingHelper(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				getAnswerList();
			}
		});
		mAnswerLoadingHelper.onCreateView(LayoutInflater.from(this), mAnswerListView);
	}

    //创建获取问题详情的网络请求
	private void getQuestionDetail() {
		mLoadingHelper.showLoadingView(mHasInited);     //显示mLoadingHelper类的加载视图
		Downloader.getInstance(this).getQuestionDetail(mQuestionId, this, null);
	}

    //获取问题回答数
	private void getQuestionCount() {
		Downloader.getInstance(this).getQuestionCount(mQuestionId, this, null);
	}

	@Override
	@SuppressWarnings("unchecked")
    /**
     * 网络成功时调用该方法
     * @param type - URL类型，即网络请求类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj) {
		super.onSuccess(type, response, obj);
		switch (type) {
		case QUESTION_DETAIL:
			mHasInited = true;
			QuestionDetail questionDetail = (QuestionDetail) response;
			updateQuestionDetail(questionDetail);
            mLoadingHelper.showContentView();
			getQuestionCount();
			getAnswerList();
			break;
		case ANSWER_DETAIL:
			mHasAnswerInited = true;
			mQuestionPage = (int) obj;
			mAnswerLoadingHelper.showContentView();
			List<AnswerWrapBean> answerDetailList = (List<AnswerWrapBean>) response;
			updateAnswerList(answerDetailList);
			break;
		case FAVOR:
			FavorBean favorBean = (FavorBean) response;
			mIsFavored = favorBean.type.equals("add");
			processBtnEnd();
			break;
		case QUESTION_COUNT:
           answerCounts=(Integer)response;
			mQuestionCountTxt.setText(String.format(getString(R.string.answer_count), (Integer) response));
			break;
		default:
			break;
		}
	}

    /**
     * 更新问题详情页面
     * @param questionDetail - 问题详情类，包含问题详情页面所需的各种域值
     */
	private void updateQuestionDetail(QuestionDetail questionDetail) {
		List<Topic> topicList = questionDetail.getTopics();                         //获取该问题所属话题列表

        //若话题列表为空，则不显示话题列表视图
		if (Utils.isCollectionEmpty(topicList)) {
			((View) mTopicGrid.getParent()).setVisibility(View.GONE);
		} else if (mTopicGrid.getAdapter() == null) {
			mTopicGrid.setAdapter(new TopicAdapter(this, topicList));
		}

		mPostQuesTimeTxt.setText(questionDetail.question.createTime);               //设置问题创建时间
		mIsFavored = questionDetail.isAttentionQuestion;                            //设置是否已关注该问题
        mQuestionTitle.setText(questionDetail.getQuestion().getQuestionName());     //设置问题标题
        mQuestionTex=questionDetail.getQuestion().getQuestionDesc()+"";             //设置问题内容

        final String html= questionDetail.getQuestion().questionDesc+"";
        if(html!=""&&html.length()>3) {
            if (html.substring(0, 3).equals("<p>"))
            {
                String[] html1 = html.split(">");
                for (int i = 1; i < html1.length; i++) {
                     html2 = html2 + html1[i] + ">" + "<br>";
                }
            }
            else
                html2=html;
        }
        else
        {
            html2 = html;
        }

        final String html3=html2;

        //新建一个异步任务
        new AsyncTask<String,String,Spanned>(){
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Spanned s) {
                super.onPostExecute(s);

                mQuestionTxt.setText(s);
            }

            @Override
            protected Spanned doInBackground(String... params) {
                Spanned sp = Html.fromHtml(html3,
                        new Html.ImageGetter() {
                            @Override
                            public Drawable getDrawable(String source) {
                                source= "http://www.027team.com"+source;
                                InputStream is = null;
                                try {
                                    is = new URL(source).openStream();
                                    Drawable d = Drawable.createFromStream(is, "src");
                                    d.setBounds(0, 0, d.getIntrinsicWidth()*3, d.getIntrinsicHeight()*3);
                                    is.close();
                                    return d;
                                } catch (Exception e) {
                                    return null;
                                }
                            }
                        }, null);
                return sp;
            }
        }.execute();
		processBtnEnd();
	}

    //获取回答列表
    private void getAnswerList() {
        //若回答列表已经完成初始化，则显示回答列表；否则显示正在加载页面
		mAnswerLoadingHelper.showLoadingView(mHasAnswerInited);
        //创建获取回答列表内容的网络请求
		Downloader.getInstance(this).getAnswerList(mQuestionId, "time", "desc", ++mQuestionPage , this,
				++mQuestionPage);
	}

    //更新回答列表视图
	private void updateAnswerList(List<AnswerWrapBean> answerDetailList) {
		if (answerDetailList != null && answerDetailList.size() > 0) {
            answerWrapBeans.clear();
			answerWrapBeans.addAll(answerDetailList);
            adapter = new AnswerListAdapter(this, answerWrapBeans);
            mAnswerListView.setAdapter(adapter);
		}
	}

	@Override
    /**
     * 网络请求失败时调用该函数，
     * 当网络请求类型为“问题详情”时，显示重新刷新页面
     * 当网络请求类型为“回答详情”时，显示重新刷新页面
     * 当网络请求类型为“关注”时，显示“关注”或“取消关注”失败提示信息
     * 当网络请求为“问题数”时，显示“0个回答”
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public void onFail(DownloadParams.PARSING_TYPE type, VolleyError error) {
		super.onFail(type, error);
		switch (type) {
		case QUESTION_DETAIL:
			if (!mHasInited) {
				mLoadingHelper.showRetryView();
			}
			break;
		case ANSWER_DETAIL:
			if (!mHasAnswerInited) {
				mAnswerLoadingHelper.showRetryView();
			}
			mAnswerListView.onRefreshComplete();
			break;
		case FAVOR:
			if (TextUtils.isEmpty(msg)) {
				toast(mIsFavored ? "取消关注失败" : "关注失败");
			} else {
				toast(msg);
			}
			processBtnEnd();
			break;
		case QUESTION_COUNT:
			mQuestionCountTxt.setText(String.format(getString(R.string.answer_count), 0));
			break;
		default:
			break;
		}
	}

    //结束“关注”按钮处理进程
	private void processBtnEnd() {
		mFavorBtn.setProgress(100);
		mFavorBtn.setText(mIsFavored ? "取消关注" :"关注");
		mFavorBtn.setEnabled(true);
	}

	@Override
    /**
     * 方法名：onClick(View v)
     * 功 能：根据发生点击事件的控件不同处理不同的点击事件
     *        控件为“关注”按钮时，请求关注该问题
     *        控件为“添加答案”按钮时，跳转到AddAnswerActivity
     *        控件为“邀请人回答”按钮时，跳转到InviteAnswerActivity
     *        控件为“问题内容”框时，跳转到QuestionShow
     * 参 数：@param v - 发生点击事件的控件
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.favor_btn:
			mFavorBtn.setEnabled(false);
			requestFavorQuestion();
			break;
		case R.id.add_answer:
			startActivityForResult(AddAnswerActivity.getStartIntent(this, mQuestionId), REQUEST_ADD_ANSWER);
			break;
		case R.id.btn_request_answer:
			startActivity(InviteAnswerActivity.getStartIntent(this, mQuestionId));
			break;
        case R.id.question:
            startActivity(QuestionShow.getStartIntent(this,mQuestionTex,mQuestionTitle0));
		}
	}

    //创建请求关注的网络请求
	private void requestFavorQuestion() {
		Downloader.getInstance(this).requestFavor(mQuestionId, this);
		mFavorBtn.setProgress(50);
	}

	@Override
    //从被调用的activity中获取result
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_ADD_ANSWER && resultCode == RESULT_OK) {
			mHasAnswerInited = false;
			mQuestionPage = 0;
			getAnswerList();
		}
	}
}
